let _config = {
    appid: 173230341,
    server: 'wss://webliveroom173230341-api.zego.im/ws',
    logLevel: 1,
    remoteLogLevel: 1,
    idName: 'A' + new Date().getTime(),
    nickName: 'A' + new Date().getTime(),
    audienceCreateRoom: false,
}
let tokenUrl = 'https://wsliveroom-alpha.zego.im:8282/token';
let roomid = window.location.href.split('=')[1];
console.log(roomid)
let token = '';
let localVideo, anchorUserId; // 主播的userid
let cdnFlvPlayerList = [];
let useLocalStreamList = [];
let isJoinLiving = false;
let anchorLianmaiStatus = false; // 主播连麦状态 观众需要拉超过两个人的流
let streamRTCList = []; // 观众拉RTC流数组

zg = new ZegoClient();
zg.config(_config);
bindListener();
// zg.setUserStateUpdate(true);


// 1. 检测设备
ZegoClient.supportDetection(function (result) {
    console.log(result)
    if (!result.webRtc) {
        alert('当前浏览器不支持webRTC')
    } else if (!result.capture) {
        alert('当前浏览器不支持捕获摄像头麦克风设备')
    } else if (!result.videoDecodeType.H264) {
        alert('浏览器不支持视频H.264编码');
    } else if (!result.videoDecodeType.VP8) {
        alert('浏览器不支持视频VP8编码');
    }
}, function (err) {
    console.error(err);
})
// 2. 获取token，登入房间
async function getToken() {
    let response = await fetch(tokenUrl + '?app_id=' + _config.appid + '&id_name=' + _config.idName);
    if (response.status >= 200 && response.status < 300) {
        await response.text().then(res => {
            token = res;
        })
    } else {
        throw new Error(response.statusText);
    }
}
// 3. 开始拉流
let btn = document.getElementById('startPlay')
btn.onclick = async function () {
    try {
        await getToken()
        zg.login(roomid, 2, token, (streamlist) => {
            console.log(streamlist);
            useLocalStreamList = streamlist;
            // 3. 拉流
            streamlist.forEach((item) => {
                if (item.stream_id.indexOf('userId') === -1) {
                    anchorUserId = item.anchor_id_name;
                    console.log('主播userId==',anchorUserId)
                }
            })
            btn.setAttribute('disabled', true)
            document.getElementById('lianmai').removeAttribute('disabled')
            document.getElementById('changeRTC').removeAttribute('disabled')
        }, err => {
            console.log(err)
        })
    } catch (err) {
        console.log(err)
    }
}

// 4.切换到L3拉流
document.getElementById('changeRTC').onclick = async function(){
    let playingCDNStream = Object.keys(cdnFlvPlayerList);
    playingCDNStream.forEach(item=>{
        deleteCdnplayer(item)
        let divCDN = document.getElementById(item);
        document.getElementsByClassName('row-remote')[0].removeChild(divCDN);
        let { div, video } = createVideoTag(true, item);
        document.getElementById('row-remote').appendChild(div);
        zg.startPlayingStream(item, video)
    })
    document.getElementById('changeRTC').setAttribute('disabled', true)
}

// cdn播放
async function cdnPlayer(userId, streamId) {
    //播放cdn
    let cdnFlvPlayer = null;
    const {
        div,
        video
    } = createVideoTag(false, streamId)
    const cdnVideoElement = video;
    document.getElementsByClassName('row-remote')[0].appendChild(div)
    // let cdnStreamID = `https://hdl-wsdemo.zego.im/livestream/zegotest-1739272706-${streamId}.flv`;
    let cdnStreamID = `https://play-memetest-aliyun.zego.im/memetest/${streamId}.flv`;
    console.log('cdnStreamID===', cdnStreamID)
    if (flvjs.isSupported()) {
        if (cdnFlvPlayer !== null) {
            cdnFlvPlayer.pause()
            cdnFlvPlayer.unload()
            cdnFlvPlayer.detachMediaElement();
            cdnFlvPlayer.destroy();
            cdnFlvPlayer = null;
        }
        cdnFlvPlayer = flvjs.createPlayer({
            type: 'flv',
            cors: true,
            isLive: true,
            url: cdnStreamID,
            hasAudio: true,
            hasVideo: true
        })
        console.log('createPlayer===')
        cdnFlvPlayer.on(flvjs.Events.LOADING_COMPLETE, function () {
            cdnFlvPlayer.play()
        })
        cdnFlvPlayer.attachMediaElement(cdnVideoElement);
        cdnFlvPlayer.load();
        cdnFlvPlayerList[streamId] = cdnFlvPlayer;
        cdnVideoElement.muted = false;
        cdnVideoElement.controls = true;
    }
}
// 删除播放CDN 
function deleteCdnplayer(streamId) {
    if (cdnFlvPlayerList[streamId]) {
        cdnFlvPlayerList[streamId].pause();
        cdnFlvPlayerList[streamId].unload();
        cdnFlvPlayerList[streamId].detachMediaElement();
        cdnFlvPlayerList[streamId].destroy();
        cdnFlvPlayerList[streamId] = null;
        delete cdnFlvPlayerList[streamId];
    }
}
// 删除所有的播放CDN 
function deleteAllCdnplayer() {
    let playingStreamList = Object.keys(cdnFlvPlayerList);
    playingStreamList.forEach(item => {
        deleteCdnplayer(item)
        let div = document.getElementById(item);
        document.getElementsByClassName('row-remote')[0].removeChild(div);
    })
    playingStreamList = [];
}
// 4. 退出房间
function logoutRoom() {
    if(isJoinLiving){
        stopLianmai('logout');
    }else{
        zg.logout()
    }
    useLocalStreamList = [];
    deleteAllCdnplayer();
    document.getElementById('startPlay').removeAttribute('disabled')
    document.getElementById('lianmai').setAttribute('disabled',true)
}

// 5. 请求与主播连麦
function requestLianmai() {
    console.log('请求与主播连麦==', anchorUserId)
    if (anchorLianmaiStatus) {
        alert('主播正在连麦，请稍后')
        return false;
    }
    document.getElementById('stop-lianmai').removeAttribute('disabled');
    document.getElementById('lianmai').setAttribute('disabled', true);
    //预览推流
    const { div, video } = createVideoTag(true, _config.idName);
    localVideo = video;
    video.setAttribute('id', 'localVideo')
    document.getElementsByClassName('row-local')[0].appendChild(div);
    zg.startPreview(localVideo, 
        { 
            video: true, 
            audio: true,
            videoQuality: 4,
            width: 640,
            height: 480,
            frameRate: 15,
            audioBitRate: 48000,
            bitRate: {
                maxBitRate: 1000,
                minBitRate: 600, 
            },
            noiseSuppression: false,
            autoGainControl: false,
            echoCancellation: true,
        }, (success) => {
        deleteAllCdnplayer();
        console.log('预览成功！', success)
        isJoinLiving = true
        // 推流
        zg.startPublishingStream(streamid = _config.idName, localVideo);
        let customContent = "joinlive"
        zg.sendCustomCommand([anchorUserId], customContent, (seq, customContent) => {
            console.log('发送自定义消息成功==', customContent)  
        }, (err, seq, customContent) => {
            console.log('发送自定义消息失败==', err, customContent)
        })
        // 转推cdn
        zg.publishTarget({
            type: 'addpush',
            streamId: _config.idName,
            pushUrl: `rtmp://publish-memetest-aliyun.zego.im/memetest/${_config.idName}`
        }, (success) => {
            console.log('转推成功==', success, 'rtmp://publish-memetest-aliyun.zego.im/memetest/' + _config.idName)
            console.log('拉流cdn地址==', `https://testplay.aliyun.zego.im/livestream/${_config.idName}.flv`)
        }, (err) => {
            console.log('转推失败==', err)
        })
        setTimeout(()=>{
            startPlayingRTCStream();
        },1000)
    }, (error) => {
        console.log('预览失败！', error)
    })
}
//开始拉rtc流
function startPlayingRTCStream() {
    console.log(useLocalStreamList)
    for (var i = 0; i < useLocalStreamList.length; i++) {
        // $('.remoteVideo').append($('<video autoplay muted playsinline controls></video>'));
        // play(useLocalStreamList[i].stream_id, $('.remoteVideo video:last-child')[0]);

        const {div, video} = createVideoTag(false, useLocalStreamList[i].stream_id)
        document.getElementById('row-remote').appendChild(div);
        zg.startPlayingStream(useLocalStreamList[i].stream_id, video);
    }
}
function play(streamId, video) {
    console.log('RTC====',streamId)
    console.log(video)
    zg.startPlayingStream(streamId, video);
    video.muted = false;
}
//停止拉RTC
function stopPlayingRTCStream() {
    for (var i = 0; i < useLocalStreamList.length; i++) {
        zg.stopPlayingStream(useLocalStreamList[i].stream_id);
        let div = document.getElementById(useLocalStreamList[i].stream_id);
        document.getElementById('row-remote').removeChild(div);
        useLocalStreamList.splice(i, 1);
    }
}
// 绑定事件
function bindListener() {
    zg.onDisconnect = function (err) {
        // 网络断开后的回调处理
        console.log('网络断开后的回调处理', err)
    }
    zg.onKickOut = function (err) {
        // 踢出房间后的回调处理
    }
    zg.onStreamUpdated = function (type, streamList) {
        console.log('流更新===', type, streamList)
        if (type == 0) {
            for (var i = 0; i < streamList.length; i++) {
                console.info(streamList[i].stream_id + ' was added');
                useLocalStreamList.push(streamList[i]);
                if (isJoinLiving) {
                    // $('.remoteVideo').append($('<video  autoplay muted playsinline controls></video>'));
                    // play(streamList[i].stream_id, $('.remoteVideo video:last-child')[0]);

                    const {div, video} = createVideoTag(false, streamList[i].stream_id)
                    document.getElementById('row-remote').appendChild(div);
                    zg.startPlayingStream(streamList[i].stream_id, video);
                }
            }
        } else if (type == 1) {
            for (var k = 0; k < useLocalStreamList.length; k++) {
                for (var j = 0; j < streamList.length; j++) {
                    if (useLocalStreamList[k].stream_id === streamList[j].stream_id) {
                        if (isJoinLiving) {
                            zg.stopPlayingStream(useLocalStreamList[k].stream_id);
                            $('.remoteVideo video:eq(' + k + ')').remove();
                        }
                        useLocalStreamList.splice(k, 1);
                        break;
                    }
                }
            }
        }
    }
    // 新观众加入
    zg.onUserStateUpdate = function (roomId, userList) {
        console.log('有新观众进入房间==', userList);
        userList.forEach((item) => {
            let p = document.createElement('p');
            p.innerHTML = `欢迎用户${item.idName}进入直播间`
            document.getElementsByClassName('user-div')[0].appendChild(p);
        })
    }
    // 主播pk 在线观众另外主播的流
    zg.onRecvReliableMessage = function (type, seq, data) {
        console.log('onRecvReliableMessage==', type, data);
        // 收到主播与主播连麦、结束连麦时，其他观众的反应

        // 不连麦的观众
        if (!isJoinLiving) {
            let streamIdList = data.trim() ? data.split(',') : [];
            anchorLianmaiStatus = streamIdList.length > 1 ? true : false;
            anchorLianmaiStatus ? 
                document.getElementById('changeRTC').setAttribute('disabled', true) : 
                document.getElementById('changeRTC').removeAttribute('disabled');
            let playingStreamList = Object.keys(cdnFlvPlayerList);
            
            if(anchorLianmaiStatus) { // 线上有两条流的情况
                // 两个streamid，连麦状态 需要停拉所有CDN，开始拉RTC
                playingStreamList.forEach(item => {
                    console.log('删除所有cdn==', item)
                    deleteCdnplayer(item)
                    let div = document.getElementById(item);
                    document.getElementsByClassName('row-remote')[0].removeChild(div);
                })
                streamIdList.forEach(item => {
                    // 渲染video
                    let { div, video } = createVideoTag(true, item);
                    document.getElementById('row-remote').appendChild(div);
                    zg.startPlayingStream(item, video);
                    streamRTCList.push(item);
                })
            }else { // 线上只有一个主播或者没有主播的情况
                // 一个streamid，单播状态，需要停拉所有RTC，开始拉CDN
                if(streamRTCList.length>0){
                    streamRTCList.forEach(item => {
                        console.log('删除所有RTC==', item)
                        zg.stopPlayingStream(item);
                        // 删除渲染video
                        let div = document.getElementById(item);
                        document.getElementById('row-remote').removeChild(div);
                    })
                    streamRTCList = [];
                }
                if(streamIdList.length>0){
                    streamIdList.forEach(item => {
                        cdnPlayer('pk主播', item);
                    })
                }else{
                    playingStreamList.forEach(item => {
                        console.log('删除所有cdn==', item)
                        deleteCdnplayer(item)
                        let div = document.getElementById(item);
                        document.getElementsByClassName('row-remote')[0].removeChild(div);
                    })
                }
            }
        }else{
            let streamIdList = data.trim() ? data.split(',') : [];
            if(streamIdList.length === 0){
                logoutRoom();
            }
        }
    }
}

// 结束连麦
function stopLianmai() {
    isJoinLiving = false
    // 删除转推CDN
    zg.publishTarget({
        type: 'delpush',
        streamId: _config.idName,
        pushUrl: `rtmp://test.aliyun.zego.im/livestream/${_config.idName}`
    }, (success) => {
        console.log('删除转推成功==')
        zg.stopPublishingStream(_config.idName);
        let video = document.getElementById(_config.idName).getElementsByTagName('video')[0];
        zg.stopPreview(video);
        stopPlayingRTCStream();
        document.getElementsByClassName('row-local')[0].innerHTML = '';
        document.getElementById('stop-lianmai').setAttribute('disabled', true);
        document.getElementById('lianmai').removeAttribute('disabled');
        if(arguments[0]==='logout'){
            zg.logout()
        }
    }, (err) => {
        console.log('删除转推失败==', err)
    })
}

function createVideoTag(bool, streamId) {
    let div = document.createElement('div');
    div.setAttribute('class', 'video');
    div.setAttribute('id', streamId)
    // let spanUserid = document.createElement('span');
    // spanUserid.setAttribute('class', 'video-userid')
    // spanUserid.innerHTML = `主播的userId: ${userId}`
    let spanStreamid = document.createElement('span');
    spanStreamid.setAttribute('class', 'video-streamid');
    spanStreamid.innerHTML = `主播的streamId: ${streamId}`
    let video = document.createElement('video');
    video.autoplay = true;
    video.muted = bool;
    div.appendChild(video);
    // div.appendChild(spanUserid);
    div.appendChild(spanStreamid);
    return {
        div,
        video
    };
}

function createJoinTag(userId) {
    let joinDiv = document.createElement('div');
    joinDiv.setAttribute('class', 'lianmai-join');
    let str = `<p>收到主播：${userId}的连麦邀请</p>
    <button onclick="agreeLianmai()" class="btn btn-primary btn-sm btn-success">同意</button>
    <button onclick="rejectLianmai()" class="btn btn-primary btn-sm btn-danger">拒绝</button>`
    joinDiv.innerHTML = str;
    document.getElementsByClassName('row-btn')[0].appendChild(joinDiv);
}

function hideJoinTag() {
    let joinDiv = document.getElementsByClassName('lianmai-join')[0];
    document.getElementsByClassName('row-btn')[0].removeChild(joinDiv);
}

function createTips(noticeStr) {
    let tipsDiv = document.createElement('div');
    tipsDiv.setAttribute('class', 'tips');
    tipsDiv.innerHTML = noticeStr;
    document.getElementsByClassName('row-btn')[0].appendChild(tipsDiv);
    setTimeout(() => {
        document.getElementsByClassName('row-btn')[0].removeChild(tipsDiv);
    }, 2000)
}